package com.fyzk.activity.lottery.togetherbuy;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.lottery.shuzicai.InfoDetailActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.fyzk.utils.SoftKeyboardUtils;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.HelpUrlConstants;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.LimitEditText;
import com.fyzk.view.LimitEditText.LimitEditTextChangeListener;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;

import http.Common.CommandUtil;
import http.StringResultBean;

@ContentView(R.layout.hm_faqi)
public class HeMaiFaQiActivity extends BaseActivity implements
        onTopTitleClickListener, LimitEditTextChangeListener {

    @ViewInject(R.id.hm_faqi_topTitle)
    private TopTitleView topView;
    @ViewInject(R.id.hm_faqi_money)
    private TextView money_tv;
    @ViewInject(R.id.hm_faqi_rengou_et)
    private LimitEditText renGou_et;
    @ViewInject(R.id.hm_faqi_rengou_tv)
    private TextView renGou_tv;//认购彩金占总额的百分百
    @ViewInject(R.id.hm_faqi_baodi_et)
    private LimitEditText baoDi_et;
    @ViewInject(R.id.hm_faqi_baodi_tv)
    private TextView baoDi_tv;//保底彩金占总额的百分百
    @ViewInject(R.id.grid_percentage)
    private GridView grid_percentage;
    @ViewInject(R.id.bottom_txt_buy)
    private TextView bottom_txt_buy;
    @ViewInject(R.id.bottom_txt_guarantee)
    private TextView bottom_txt_guarantee;
    @ViewInject(R.id.amount_pay)
    private TextView amount_pay;
    @ViewInject(R.id.send_together)
    private Button send_together;
    @ViewInject(R.id.rgp_open_type)
    private RadioGroup rgp_open_type;
    @ViewInject(R.id.hm_faqi_title_et)
    private EditText title_et;
    @ViewInject(R.id.hm_faqi_content_et)
    private EditText content_et;
    private String titleStr;
    private String contentStr;
    @ViewInject(R.id.hm_faqi_add_infor)
    private CheckBox addInfors_cb;
    @ViewInject(R.id.hm_faqi_title_ll)
    private LinearLayout title_ll;

    private int baoMiCheck = 1;
    //数据
    private String lotteryId;
    private String phase;
    private String betCode;
    private int oneAmount;
    private int amt;
    private int money;
    private double leftMoney;
    private int beiShu;
    private String expectedPrize;

    //彩金不足提醒对话框
    private AlertDialog leftMoneyLowDialog = null;

    private final int ALLOPEN = 5;
    private final int ENDOPEN = 2;
    private final int FOLLOWOPEN = 3;
    private final int NEVEROPEN = 1;
    SparseBooleanArray mCheckItems;
    private int visibility = FOLLOWOPEN;

    private double payAmt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        getIntentInfor();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void finish() {
        // 隐藏键盘
        if (null != renGou_et) {
            SoftKeyboardUtils.hintSoftKeyboard(this.getApplicationContext(), renGou_et);
        }
        super.finish();
    }

    /**
     * 发起合买
     */
    private void faQiHeMai() {
        if (payAmt > 0) {
            try {
                if (!title_et.getText().toString().equals("")) {
                    titleStr = title_et.getText().toString();
                }
                if (!content_et.getText().toString().equals("")) {
                    contentStr = content_et.getText().toString();
                }
                if (!addInfors_cb.isChecked()) {
                    titleStr = "";
                    contentStr = "";
                }

                JSONObject request_json = new JSONObject();
                request_json.put("multiple", beiShu);
                request_json.put("lotteryType", lotteryId);
                request_json.put("phase", phase);
                request_json.put("amount", money * 100);
                request_json.put("oneAmount", oneAmount * 100);
                request_json.put("buyAmount", renGou_et.getTextNum() * 100);
                request_json.put("minAmount", 100);
                request_json.put("expectedPrize", expectedPrize);
                int percentage = grid_percentage.getCheckedItemPosition();
                if (percentage == -1) {
                    percentage = 0;
                } else {
                    percentage += 1;
                }
                request_json.put("commisionRatio", percentage);//提成比例
                request_json.put("safeAmount", baoDi_et.getTextNum() * 100);
                request_json.put("betcode", betCode);
                request_json.put("visibility", visibility);
                request_json.put("title", titleStr);
                request_json.put("description", contentStr);
                httpPostJson(CommandUtil.HEMAI_FAQI, Commands.HEMAI_FAQI, request_json, true);
            } catch (JSONException e) {

            }
        } else {
            showToast("认购彩金+保底彩金需大于0米");
        }

    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        switch (requestCode) {
            case CommandUtil.HEMAI_FAQI://"caseId":"1706050000001594"
                try {
                    JSONObject jsonObject = new JSONObject(resultBean.getData());
                    final String caseId = jsonObject.getString("caseId");
                    MySharedPreferences.getInstance().setBetCodeBean(Integer.parseInt(lotteryId), new ArrayList<>());
                    new AlertDialog.Builder(getContext()).setMessage("发起合买成功").setPositiveButton
                            ("查看详情", new DialogInterface.OnClickListener() {


                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    setResult(IntentParamUtils.ZHIFU_RESULT);
                                    HeMaiFaQiActivity.this.finish();
                                    Intent intent = new Intent(getContext(), HeMaiGenDanActivity.class);
                                    intent.putExtra(IntentParamUtils.HM_HALLDETAIL_ID, caseId);
                                    getContext().startActivity(intent);
                                }
                            }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            setResult(IntentParamUtils.ZHIFU_RESULT);
                            HeMaiFaQiActivity.this.finish();
                        }
                    }).create().show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }

    }

    private void getIntentInfor() {
        Intent intent = getIntent();
        lotteryId = intent.getStringExtra(IntentParamUtils.LOTTERYID);
        phase = intent.getStringExtra(IntentParamUtils.PERIOD);
        betCode = intent.getStringExtra(IntentParamUtils.BETCODE);
        oneAmount = intent.getIntExtra(IntentParamUtils.ONEAMOUNT, 0);
        money = (int) intent.getLongExtra(IntentParamUtils.MONEY, 0);
        leftMoney = intent.getDoubleExtra(IntentParamUtils.LEFTMONEY, 0);
        beiShu = intent.getIntExtra(IntentParamUtils.MULTIPLE, 0);
        expectedPrize = intent.getStringExtra(IntentParamUtils.EXPECTEDPRIZE);
    }

    private PercentageAdapter percentageAdapter;

    private void initView() {
        addInfors_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    title_ll.setVisibility(View.VISIBLE);
                } else {
                    title_ll.setVisibility(View.GONE);
                }
            }
        });
        titleStr = AppLotteryInfos.getLotteryName(lotteryId) + getString(R.string.hm_faqi_title);
        contentStr = AppLotteryInfos.getLotteryName(lotteryId) + getString(R.string.hm_faqi_content);
        title_et.setHint(titleStr);
        content_et.setHint(contentStr);
        topView.setCenterText(R.string.hm_faqi);
        topView.setRightVisible(View.VISIBLE);
        topView.setLeftVisible(View.VISIBLE);
        topView.setRightImg(R.drawable.icon_problem);
        topView.setOnTitleClickListener(this);
        renGou_et.setMax(money);
        renGou_et.setHint("最低认购1米");
        renGou_et.setEditTextChangeListener(this);
        baoDi_et.setMax(money);
        baoDi_et.setHint("最高可保底" + baoDi_et.getMax() + "米");
        baoDi_et.setEditTextChangeListener(this);
        money_tv.setText("方案彩金" + money + "米,总份数" + money + "份,每份1米");
        grid_percentage.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
        ArrayList<PercentageItem> percentages = new ArrayList<>();
        percentages.add(new PercentageItem("1%", false));
        percentages.add(new PercentageItem("2%", false));
        percentages.add(new PercentageItem("3%", false));
        percentages.add(new PercentageItem("4%", false));
        percentages.add(new PercentageItem("5%", false));
        percentages.add(new PercentageItem("6%", false));
        percentages.add(new PercentageItem("7%", false));
        percentages.add(new PercentageItem("8%", false));
        percentages.add(new PercentageItem("9%", false));
        percentages.add(new PercentageItem("10%", false));
        percentageAdapter = new PercentageAdapter(percentages);
        mCheckItems = grid_percentage.getCheckedItemPositions();
        grid_percentage.setAdapter(percentageAdapter);
        rgp_open_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_allopen:
                        visibility = ALLOPEN;
                        break;
                    case R.id.rb_endopen:
                        visibility = ENDOPEN;
                        break;
                    case R.id.rb_followopen:
                        visibility = FOLLOWOPEN;
                        break;
                    case R.id.rb_neveropen:
                        visibility = NEVEROPEN;
                        break;
                }
            }
        });
        send_together.setOnClickListener(this);
    }

    private AlertDialog jcAlertDialog = null;

    @Override
    public void onClick(View view) {
        if (!yanZheng()) {
            return;
        }
        if (leftMoney < payAmt) {
            if (leftMoneyLowDialog == null) {
                leftMoneyLowDialog = new AlertDialog.Builder(this).setTitle("投注提示")
                        .setPositiveButton("去充值", new
                                DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                        Intent intent = new Intent(HeMaiFaQiActivity.this,
                                                RechargeActivity.class);
                                        HeMaiFaQiActivity.this.startActivity(intent);
                                    }
                                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).create();
            }
            leftMoneyLowDialog.setMessage("彩金不足,彩金" + leftMoney +
                    "米，需支付" + payAmt + "米，还差" + AppUtil.formatToYuanLXS(payAmt - leftMoney) + "米");
            leftMoneyLowDialog.show();
        } else {
            if (AppLotteryInfos.isJC(Integer.parseInt(lotteryId))) {
                if (payAmt < money) {
                    if (jcAlertDialog == null) {
                        jcAlertDialog = new AlertDialog.Builder(this).setMessage("为保证最终出票的赔率为当前赔率，竞彩发起合买需：认购彩金+保底彩金=订单总彩金").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        }).create();
                    }
                    jcAlertDialog.show();
                } else {
                    faQiHeMai();
                }
            } else {
                faQiHeMai();
            }
        }
    }

    private class PercentageItem {
        public PercentageItem(String percentage, boolean isselect) {
            this.isselect = isselect;
            this.percentage = percentage;
        }

        String percentage;
        boolean isselect;
    }


    private class PercentageAdapter extends BaseAdapter {

        private ArrayList<PercentageItem> percentages;

        public PercentageAdapter(ArrayList<PercentageItem> percentages) {
            this.percentages = percentages;
        }

        @Override
        public int getCount() {
            return this.percentages.size();
        }

        @Override
        public Object getItem(int position) {
            return this.percentages.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = View.inflate(HeMaiFaQiActivity.this, R.layout.item_percentage, null);
            PercentageItem item = this.percentages.get(position);
            item.isselect = mCheckItems.get(position);
            LogUtil.v(mCheckItems.get(position) + "");
            ((CheckBox) convertView).setOnCheckedChangeListener(null);
            ((CheckBox) convertView).setChecked(item.isselect);
            final int index = position;
            ((CheckBox) convertView).setOnCheckedChangeListener(new CompoundButton
                    .OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    grid_percentage.setItemChecked(index, isChecked);
                    percentageAdapter.notifyDataSetChanged();
                }
            });

            ((CheckBox) convertView).setText(item.percentage);

            return convertView;
        }

    }


    @Override
    public void onLeftClick() {
        // TODO Auto-generated method stub
        // 隐藏键盘
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        setResult(-1);
        finish();
    }

    @Override
    public void onCenterClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRightClick() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(getContext(), InfoDetailActivity.class);
        intent.putExtra(IntentParamUtils.TITLE, getHelpTitle());
        intent.putExtra(IntentParamUtils.URL, getHelpUrl());
        startActivity(intent);
    }

    @Override
    public void onRight2Click() {
        // TODO Auto-generated method stub

    }

    public String getHelpUrl() {
        return HelpUrlConstants.Help_HM;
    }

    public String getHelpTitle() {
        return getString(R.string.help_hemai);
    }

    @Override
    public void changText() {
        renGou_et.setMax(money - baoDi_et.getTextNum());
        baoDi_et.setMax(money - renGou_et.getTextNum());
        baoDi_et.setHint("最高可保底" + baoDi_et.getMax() + "米");
        renGou_tv.setText(getBaiFenBi(renGou_et.getTextNum(), money) + "%");
        baoDi_tv.setText(getBaiFenBi(baoDi_et.getTextNum(), money) + "%");
        payAmt = renGou_et.getTextNum() + baoDi_et.getTextNum();

        bottom_txt_buy.setText("认购" + renGou_et.getTextNum() + "米");
        bottom_txt_guarantee.setText("保底" + baoDi_et.getTextNum() + "米");
        String all_moneystr = "共" + payAmt + "米";
        amount_pay.setText(Html.fromHtml(all_moneystr));
    }

    private int getBaiFenBi(int buyMoney, int totalAmount) {
        if (buyMoney == 0 || totalAmount == 0) {
            return 0;
        }
        int result = (int) (buyMoney * 1.0 / totalAmount * 100);
        return result == 0 ? 1 : result;
    }


    /**
     * 非空验证
     */
    private boolean isNull(EditText editText) {
        if (editText.getText() == null
                || editText.getText().toString().equals("")) {
            editText.requestFocus();
            return true;
        }
        return false;
    }

    private boolean yanZheng() {
        if (isNull(renGou_et)) {
            AppToast.getToast().show("认购彩金不能为空");
            return false;
        }
        if (renGou_et.getTextNum() == 0) {
            AppToast.getToast().show("请至少认购1米");
            return false;
        }
        if (isNull(baoDi_et)) {
            baoDi_et.setText(0 + "");
        }

        return true;
    }

    /**
     * 认购彩金加保底彩金 大于20%
     *
     * @return
     */
    private boolean yanZhengRenGou() {
        int renGou = renGou_et.getTextNum();
        int baoDi = baoDi_et.getTextNum();

        return ((renGou + baoDi) * 1.0 / money * 100) < 20;
    }

}
